<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学习时间管理 - 苹果风格</title>
    
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Chart.js CDN -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <!-- Font Awesome CDN -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <script>
        // 自定义Tailwind配置以匹配苹果风格
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'apple-dark': '#1D1D1F',
                        'apple-gray': '#86868B',
                        'apple-light-gray': '#E8E8ED',
                        'apple-blue': '#0071E3',
                        'apple-hover': '#F5F5F7',
                        'apple-progress': '#E1F5FE',
                        'apple-delete': '#FF3B30'
                    },
                    fontFamily: {
                        'sf-pro': ['-apple-system', 'BlinkMacSystemFont', 'Segoe UI', 'Roboto', 'Helvetica', 'Arial', 'sans-serif']
                    },
                    borderRadius: {
                        'apple': '8px'
                    },
                    animation: {
                        'fade-in': 'fadeIn 0.8s ease-out',
                        'scale-hover': 'scaleHover 0.2s ease-out'
                    },
                    keyframes: {
                        fadeIn: {
                            '0%': { opacity: '0', transform: 'translateY(10px)' },
                            '100%': { opacity: '1', transform: 'translateY(0)' }
                        },
                        scaleHover: {
                            '0%': { transform: 'scale(1)' },
                            '100%': { transform: 'scale(1.03)' }
                        }
                    }
                }
            }
        }
    </script>
    
    <style>
        /* 自定义样式 */
        .countdown-number {
            transition: all 0.3s ease-in-out;
        }
        
        .progress-bar {
            transition: width 0.5s linear;
        }
        
        .glass-effect {
            background: rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }
        
        /* 苹果风格复选框 */
        .apple-checkbox {
            -webkit-appearance: none;
            appearance: none;
            width: 18px;
            height: 18px;
            border: 1px solid #E8E8ED;
            border-radius: 4px;
            outline: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .apple-checkbox:checked {
            background-color: #0071E3;
            border-color: #0071E3;
        }
        
        .apple-checkbox:checked::before {
            content: '✓';
            display: block;
            color: white;
            font-size: 12px;
            font-weight: bold;
            text-align: center;
            line-height: 18px;
        }
    </style>
</head>
<body class="font-sf-pro bg-white text-apple-dark min-h-screen">
    <div class="max-w-6xl mx-auto px-4 py-8">
        <!-- 页面标题 -->
        <header class="text-center mb-12 animate-fade-in">
            <h1 class="text-3xl md:text-4xl font-light text-apple-dark mb-2">学习时间管理</h1>
            <p class="text-apple-gray text-sm">高效规划，专注学习</p>
        </header>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- 左侧列：倒计时和计划 -->
            <div class="space-y-8">
                <!-- 自定义日期倒计时模块 -->
                <section class="bg-white p-6 rounded-apple animate-fade-in" style="animation-delay: 0.1s">
                    <div class="text-center">
                        <input type="text" 
                               id="target-name" 
                               class="text-apple-gray text-sm text-center bg-transparent border-none outline-none mb-4 w-full" 
                               placeholder="输入目标名称（如：期末考试）"
                               value="期末考试">
                        
                        <div class="flex justify-center items-end space-x-2 mb-2">
                            <div class="text-center">
                                <div id="days" class="countdown-number text-5xl md:text-6xl font-light text-apple-dark">00</div>
                                <div class="text-apple-gray text-sm mt-1">天</div>
                            </div>
                            <div class="text-4xl md:text-5xl font-light text-apple-dark pb-2">:</div>
                            <div class="text-center">
                                <div id="hours" class="countdown-number text-5xl md:text-6xl font-light text-apple-dark">00</div>
                                <div class="text-apple-gray text-sm mt-1">时</div>
                            </div>
                            <div class="text-4xl md:text-5xl font-light text-apple-dark pb-2">:</div>
                            <div class="text-center">
                                <div id="minutes" class="countdown-number text-5xl md:text-6xl font-light text-apple-dark">00</div>
                                <div class="text-apple-gray text-sm mt-1">分</div>
                            </div>
                            <div class="text-4xl md:text-5xl font-light text-apple-dark pb-2">:</div>
                            <div class="text-center">
                                <div id="seconds" class="countdown-number text-5xl md:text-6xl font-light text-apple-dark">00</div>
                                <div class="text-apple-gray text-sm mt-1">秒</div>
                            </div>
                        </div>
                        
                        <input type="date" 
                               id="target-date" 
                               class="text-apple-gray text-sm text-center border border-apple-light-gray rounded-apple px-3 py-2 mt-4 focus:border-apple-blue focus:outline-none transition-colors"
                               value="2024-12-31">
                    </div>
                </section>

                <!-- 每日计划管理模块 -->
                <section class="bg-white p-6 rounded-apple animate-fade-in" style="animation-delay: 0.3s">
                    <div class="flex items-center justify-between mb-4">
                        <h2 class="text-lg font-medium text-apple-dark">今日计划</h2>
                        <button id="add-plan" class="w-8 h-8 rounded-full bg-apple-blue text-white flex items-center justify-center hover:scale-105 transition-transform">
                            <i class="fas fa-plus text-xs"></i>
                        </button>
                    </div>
                    
                    <div id="plan-list" class="space-y-3">
                        <!-- 计划项将通过JS动态添加 -->
                    </div>
                    
                    <div class="mt-4 flex space-x-2">
                        <input type="text" 
                               id="new-plan-input" 
                               class="flex-1 border border-apple-light-gray rounded-apple px-3 py-2 focus:border-apple-blue focus:outline-none transition-colors" 
                               placeholder="添加新的学习计划...">
                        <button id="confirm-add" class="px-4 py-2 bg-apple-blue text-white rounded-apple hover:bg-opacity-90 transition-colors">
                            添加
                        </button>
                    </div>
                </section>
            </div>

            <!-- 右侧列：学习时长和图表 -->
            <div class="space-y-8">
                <!-- 每日学习时长记录模块 -->
                <section class="bg-white p-6 rounded-apple animate-fade-in" style="animation-delay: 0.2s">
                    <h2 class="text-lg font-medium text-apple-dark mb-4">今日学习时长</h2>
                    
                    <!-- 实时计时器 -->
                    <div class="mb-6 p-4 bg-apple-hover rounded-apple">
                        <div class="text-center mb-3">
                            <div class="flex justify-center items-end space-x-1">
                                <div class="text-center">
                                    <div id="timer-hours" class="text-3xl font-light text-apple-dark">00</div>
                                    <div class="text-apple-gray text-xs mt-1">时</div>
                                </div>
                                <div class="text-2xl font-light text-apple-dark pb-1">:</div>
                                <div class="text-center">
                                    <div id="timer-minutes" class="text-3xl font-light text-apple-dark">00</div>
                                    <div class="text-apple-gray text-xs mt-1">分</div>
                                </div>
                                <div class="text-2xl font-light text-apple-dark pb-1">:</div>
                                <div class="text-center">
                                    <div id="timer-seconds" class="text-3xl font-light text-apple-dark">00</div>
                                    <div class="text-apple-gray text-xs mt-1">秒</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="flex justify-center space-x-3">
                            <button id="start-timer" class="px-4 py-2 bg-apple-blue text-white rounded-apple hover:bg-opacity-90 transition-colors text-sm">
                                <i class="fas fa-play mr-1"></i>开始
                            </button>
                            <button id="pause-timer" class="px-4 py-2 bg-apple-gray text-white rounded-apple hover:bg-opacity-90 transition-colors text-sm" disabled>
                                <i class="fas fa-pause mr-1"></i>暂停
                            </button>
                            <button id="reset-timer" class="px-4 py-2 bg-apple-light-gray text-apple-dark rounded-apple hover:bg-opacity-90 transition-colors text-sm">
                                <i class="fas fa-redo mr-1"></i>重置
                            </button>
                        </div>
                    </div>
                    
                    <div class="flex items-center space-x-4 mb-4">
                        <div class="flex-1">
                            <label class="text-apple-gray text-sm mb-1 block">手动输入学习时长</label>
                            <div class="flex space-x-2">
                                <input type="number" 
                                       id="study-hours" 
                                       min="0" 
                                       class="w-16 border border-apple-light-gray rounded-apple px-3 py-2 text-center focus:border-apple-blue focus:outline-none transition-colors" 
                                       placeholder="时"
                                       value="0">
                                <span class="text-apple-gray self-center">:</span>
                                <input type="number" 
                                       id="study-minutes" 
                                       min="0" 
                                       max="59" 
                                       class="w-16 border border-apple-light-gray rounded-apple px-3 py-2 text-center focus:border-apple-blue focus:outline-none transition-colors" 
                                       placeholder="分"
                                       value="0">
                            </div>
                        </div>
                        
                        <button id="confirm-time" class="px-4 py-2 bg-apple-blue text-white rounded-apple hover:bg-apple-hover hover:text-apple-blue transition-colors self-end">
                            确认
                        </button>
                    </div>
                    
                    <div class="mb-4">
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-apple-gray text-sm">今日累计</span>
                            <span id="total-time" class="text-apple-dark font-medium">0小时 0分钟</span>
                        </div>
                        
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-apple-gray text-sm">总学习时长</span>
                            <span id="total-study-time" class="text-apple-dark font-medium">0小时 0分钟</span>
                        </div>
                        
                        <div class="flex items-center space-x-3">
                            <span class="text-apple-gray text-sm whitespace-nowrap">目标:</span>
                            <input type="number" 
                                   id="target-hours" 
                                   min="0" 
                                   class="w-12 border border-apple-light-gray rounded-apple px-2 py-1 text-center text-sm focus:border-apple-blue focus:outline-none transition-colors" 
                                   value="4">
                            <span class="text-apple-gray text-sm">小时</span>
                        </div>
                    </div>
                    
                    <div class="w-full bg-apple-light-gray rounded-full h-2">
                        <div id="progress-bar" class="progress-bar h-2 rounded-full bg-apple-blue" style="width: 0%"></div>
                    </div>
                </section>

                <!-- 近七日学习时长曲线模块 -->
                <section class="bg-white p-6 rounded-apple animate-fade-in" style="animation-delay: 0.4s">
                    <h2 class="text-apple-gray text-sm mb-4 text-center">近7日学习时长</h2>
                    <div class="w-full" style="height: 250px">
                        <canvas id="study-chart"></canvas>
                    </div>
                </section>
            </div>
        </div>
    </div>

    <script>
        // 数据存储和管理
        const AppData = {
            targetDate: null,
            targetName: '期末考试',
            dailyStudyTime: 0,
            targetStudyHours: 4,
            studyPlans: [],
            studyHistory: [],
            
            // 计时器相关变量
            timerInterval: null,
            timerRunning: false,
            timerSeconds: 0,
            timerTotalSeconds: 0,
            
            init() {
                this.loadFromStorage();
                this.setupEventListeners();
                this.startCountdown();
                this.renderStudyPlans();
                this.updateStudyTimeDisplay();
                this.initChart();
                this.updateTimerDisplay();
            },
            
            loadFromStorage() {
                const saved = localStorage.getItem('studyTimeManager');
                if (saved) {
                    const data = JSON.parse(saved);
                    this.targetDate = data.targetDate ? new Date(data.targetDate) : new Date('2024-12-31');
                    this.targetName = data.targetName || '期末考试';
                    this.dailyStudyTime = data.dailyStudyTime || 0;
                    this.targetStudyHours = data.targetStudyHours || 4;
                    this.studyPlans = data.studyPlans || [];
                    this.studyHistory = data.studyHistory || [];
                    
                    // 更新UI
                    document.getElementById('target-date').value = this.targetDate.toISOString().split('T')[0];
                    document.getElementById('target-name').value = this.targetName;
                    document.getElementById('target-hours').value = this.targetStudyHours;
                    this.timerTotalSeconds = data.timerTotalSeconds || 0;
                } else {
                    this.targetDate = new Date('2024-12-31');
                    document.getElementById('target-date').value = '2024-12-31';
                }
            },
            
            saveToStorage() {
                const data = {
                    targetDate: this.targetDate ? this.targetDate.toISOString() : null,
                    targetName: this.targetName,
                    dailyStudyTime: this.dailyStudyTime,
                    targetStudyHours: this.targetStudyHours,
                    studyPlans: this.studyPlans,
                    studyHistory: this.studyHistory,
                    timerTotalSeconds: this.timerTotalSeconds
                };
                localStorage.setItem('studyTimeManager', JSON.stringify(data));
            },
            
            setupEventListeners() {
                // 目标日期变更
                document.getElementById('target-date').addEventListener('change', (e) => {
                    this.targetDate = new Date(e.target.value);
                    this.targetName = document.getElementById('target-name').value;
                    this.saveToStorage();
                });
                
                // 目标名称变更
                document.getElementById('target-name').addEventListener('change', (e) => {
                    this.targetName = e.target.value;
                    this.saveToStorage();
                });
                
                // 目标学习时长变更
                document.getElementById('target-hours').addEventListener('change', (e) => {
                    this.targetStudyHours = parseInt(e.target.value) || 4;
                    this.saveToStorage();
                    this.updateStudyTimeDisplay();
                });
                
                // 添加学习时间
                document.getElementById('confirm-time').addEventListener('click', () => {
                    const hours = parseInt(document.getElementById('study-hours').value) || 0;
                    const minutes = parseInt(document.getElementById('study-minutes').value) || 0;
                    const totalMinutes = hours * 60 + minutes;
                    
                    if (totalMinutes > 0) {
                        this.dailyStudyTime += totalMinutes;
                        this.recordStudyTime(totalMinutes);
                        this.updateStudyTimeDisplay();
                        this.saveToStorage();
                        
                        // 清空输入
                        document.getElementById('study-hours').value = '0';
                        document.getElementById('study-minutes').value = '0';
                    }
                });
                
                // 添加学习计划
                document.getElementById('confirm-add').addEventListener('click', () => {
                    this.addStudyPlan();
                });
                
                document.getElementById('new-plan-input').addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        this.addStudyPlan();
                    }
                });
                
                document.getElementById('add-plan').addEventListener('click', () => {
                    this.addStudyPlan();
                });
                
                // 计时器控制
                document.getElementById('start-timer').addEventListener('click', () => {
                    this.startTimer();
                });
                
                document.getElementById('pause-timer').addEventListener('click', () => {
                    this.pauseTimer();
                });
                
                document.getElementById('reset-timer').addEventListener('click', () => {
                    this.resetTimer();
                });
            },
            
            addStudyPlan() {
                const input = document.getElementById('new-plan-input');
                const text = input.value.trim();
                
                if (text) {
                    this.studyPlans.push({
                        id: Date.now(),
                        text: text,
                        completed: false
                    });
                    
                    input.value = '';
                    this.renderStudyPlans();
                    this.saveToStorage();
                }
            },
            
            renderStudyPlans() {
                const container = document.getElementById('plan-list');
                container.innerHTML = '';
                
                this.studyPlans.forEach(plan => {
                    const planElement = document.createElement('div');
                    planElement.className = 'flex items-center justify-between group hover:bg-apple-hover rounded-apple px-3 py-2 transition-colors';
                    planElement.innerHTML = `
                        <div class="flex items-center space-x-3">
                            <input type="checkbox" 
                                   class="apple-checkbox" 
                                   ${plan.completed ? 'checked' : ''}
                                   onchange="AppData.togglePlan(${plan.id})">
                            <span class="${plan.completed ? 'line-through text-apple-gray' : 'text-apple-dark'}">${plan.text}</span>
                        </div>
                        <button class="opacity-0 group-hover:opacity-100 text-apple-gray hover:text-apple-delete transition-opacity"
                                onclick="AppData.deletePlan(${plan.id})">
                            <i class="fas fa-times"></i>
                        </button>
                    `;
                    container.appendChild(planElement);
                });
                
                if (this.studyPlans.length === 0) {
                    container.innerHTML = '<p class="text-apple-gray text-center py-4">暂无学习计划</p>';
                }
            },
            
            togglePlan(id) {
                const plan = this.studyPlans.find(p => p.id === id);
                if (plan) {
                    plan.completed = !plan.completed;
                    this.renderStudyPlans();
                    this.saveToStorage();
                }
            },
            
            deletePlan(id) {
                this.studyPlans = this.studyPlans.filter(p => p.id !== id);
                this.renderStudyPlans();
                this.saveToStorage();
            },
            
            // 计时器方法
            startTimer() {
                if (!this.timerRunning) {
                    this.timerRunning = true;
                    this.timerInterval = setInterval(() => {
                        this.timerSeconds++;
                        this.timerTotalSeconds++;
                        this.updateTimerDisplay();
                    }, 1000);
                    
                    document.getElementById('start-timer').disabled = true;
                    document.getElementById('pause-timer').disabled = false;
                    document.getElementById('start-timer').classList.remove('bg-apple-blue');
                    document.getElementById('start-timer').classList.add('bg-apple-gray');
                }
            },
            
            pauseTimer() {
                if (this.timerRunning) {
                    this.timerRunning = false;
                    clearInterval(this.timerInterval);
                    
                    // 将计时器时间添加到今日学习时长
                    if (this.timerSeconds > 0) {
                        this.dailyStudyTime += this.timerSeconds;
                        this.recordStudyTime(this.timerSeconds);
                        this.updateStudyTimeDisplay();
                        this.saveToStorage();
                        this.timerSeconds = 0;
                    }
                    
                    document.getElementById('start-timer').disabled = false;
                    document.getElementById('pause-timer').disabled = true;
                    document.getElementById('start-timer').classList.remove('bg-apple-gray');
                    document.getElementById('start-timer').classList.add('bg-apple-blue');
                }
            },
            
            resetTimer() {
                this.pauseTimer();
                this.timerSeconds = 0;
                this.timerTotalSeconds = 0;
                this.updateTimerDisplay();
            },
            
            updateTimerDisplay() {
                const hours = Math.floor(this.timerSeconds / 3600);
                const minutes = Math.floor((this.timerSeconds % 3600) / 60);
                const seconds = this.timerSeconds % 60;
                
                document.getElementById('timer-hours').textContent = hours.toString().padStart(2, '0');
                document.getElementById('timer-minutes').textContent = minutes.toString().padStart(2, '0');
                document.getElementById('timer-seconds').textContent = seconds.toString().padStart(2, '0');
            },
            
            recordStudyTime(minutes) {
                const today = new Date().toDateString();
                const hours = minutes / 60;
                
                // 查找今天是否已有记录
                const todayIndex = this.studyHistory.findIndex(entry => entry.date === today);
                
                if (todayIndex !== -1) {
                    this.studyHistory[todayIndex].hours += hours;
                } else {
                    // 保持最近7天记录
                    if (this.studyHistory.length >= 7) {
                        this.studyHistory.shift();
                    }
                    this.studyHistory.push({
                        date: today,
                        hours: hours,
                        displayDate: this.formatDisplayDate(new Date())
                    });
                }
                
                this.updateChart();
            },
            
            formatDisplayDate(date) {
                return `${date.getMonth() + 1}/${date.getDate()}`;
            },
            
            updateStudyTimeDisplay() {
                const totalHours = Math.floor(this.dailyStudyTime / 60);
                const totalMinutes = this.dailyStudyTime % 60;
                
                document.getElementById('total-time').textContent = 
                    `${totalHours}小时 ${totalMinutes}分钟`;
                
                // 计算总学习时长（今日累计 + 计时器累计）
                const totalStudySeconds = this.dailyStudyTime * 60 + this.timerTotalSeconds;
                const totalStudyHours = Math.floor(totalStudySeconds / 3600);
                const totalStudyMinutes = Math.floor((totalStudySeconds % 3600) / 60);
                
                document.getElementById('total-study-time').textContent = 
                    `${totalStudyHours}小时 ${totalStudyMinutes}分钟`;
                
                const targetMinutes = this.targetStudyHours * 60;
                const progress = targetMinutes > 0 ? Math.min((this.dailyStudyTime / targetMinutes) * 100, 100) : 0;
                
                document.getElementById('progress-bar').style.width = `${progress}%`;
            },
            
            startCountdown() {
                setInterval(() => {
                    if (this.targetDate) {
                        const now = new Date();
                        const diff = this.targetDate - now;
                        
                        if (diff > 0) {
                            const days = Math.floor(diff / (1000 * 60 * 60 * 24));
                            const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                            const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                            const seconds = Math.floor((diff % (1000 * 60)) / 1000);
                            
                            document.getElementById('days').textContent = days.toString().padStart(2, '0');
                            document.getElementById('hours').textContent = hours.toString().padStart(2, '0');
                            document.getElementById('minutes').textContent = minutes.toString().padStart(2, '0');
                            document.getElementById('seconds').textContent = seconds.toString().padStart(2, '0');
                        }
                    }
                }, 1000);
            },
            
            initChart() {
                const ctx = document.getElementById('study-chart').getContext('2d');
                
                this.chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: '学习时长',
                            data: [],
                            borderColor: '#0071E3',
                            backgroundColor: 'rgba(0, 113, 227, 0.1)',
                            borderWidth: 2,
                            pointBackgroundColor: '#ffffff',
                            pointBorderColor: '#0071E3',
                            pointBorderWidth: 2,
                            pointRadius: 4,
                            pointHoverRadius: 8,
                            fill: true,
                            tension: 0.4
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                                titleColor: '#1D1D1F',
                                bodyColor: '#1D1D1F',
                                borderColor: '#E8E8ED',
                                borderWidth: 1,
                                cornerRadius: 8,
                                displayColors: false,
                                callbacks: {
                                    label: function(context) {
                                        return `学习时长: ${context.parsed.y.toFixed(1)}小时`;
                                    }
                                }
                            }
                        },
                        scales: {
                            x: {
                                grid: {
                                    display: false
                                },
                                ticks: {
                                    color: '#86868B',
                                    font: {
                                        family: '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif'
                                    }
                                }
                            },
                            y: {
                                beginAtZero: true,
                                grid: {
                                    color: '#E8E8ED',
                                    drawBorder: false
                                },
                                ticks: {
                                    color: '#86868B',
                                    font: {
                                        family: '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif'
                                    },
                                    callback: function(value) {
                                        return value + 'h';
                                    }
                                }
                            }
                        },
                        interaction: {
                            intersect: false,
                            mode: 'index'
                        }
                    }
                });
                
                this.updateChart();
            },
            
            updateChart() {
                if (this.chart) {
                    const labels = this.studyHistory.map(entry => entry.displayDate);
                    const data = this.studyHistory.map(entry => entry.hours);
                    
                    this.chart.data.labels = labels;
                    this.chart.data.datasets[0].data = data;
                    this.chart.update();
                }
            }
        };
        
        // 初始化应用
        document.addEventListener('DOMContentLoaded', () => {
            AppData.init();
        });
    </script>
</body>
</html>